package cmdbControllers

import (
	"fmt"
	"github.com/astaxie/beego"
	//"fmt"
	"lazyops_go/models"
	"lazyops_go/tasks"
	"lazyops_go/tools"
	//"lazyops_go/tools"
	//"time"
)

type AssetController struct {
	beego.Controller
}

func (c *AssetController) IndexAsset() {
	cur_page,_ := c.GetInt(":page",1)
	asset_list :=models.QueryAssetAll()
	idc_list := models.QueryIdcAll()
	label_list := models.QueryLabelAll()
	lguser_list := models.QueryLgUserAll()
	cur_user_menus := c.GetSession("cur_user_menus")
	cur_user := c.GetSession("cur_user")
	data_list := models.QueryAssetPage(cur_page)
	page:=tools.CreatePaging(cur_page,12,len(asset_list))
	c.Data["page"] = page

	c.Data["cur_user"] = cur_user
	c.Data["cur_user_menus"] = cur_user_menus
	c.Data["data_list"] = data_list
	c.Data["idc_list"] = idc_list
	c.Data["label_list"] = label_list
	c.Data["lguser_list"] = lguser_list
	c.Data["label"] = "主机管理"
	c.XSRFExpire = 7200
	c.Data["xsrf_token"] = c.XSRFToken()
	c.Layout = "base/base.html"
	c.LayoutSections = make(map[string]string)
	c.LayoutSections["Scripts"] = "cmdb/assetjs.html"
	c.TplName = "cmdb/asset.html"
}

func (c *AssetController) SearchAsset() {
	key := c.Ctx.Input.Param(":key")
	data_list :=models.QueryAssetSearch(key)
	idc_list := models.QueryIdcAll()
	label_list := models.QueryLabelAll()
	lguser_list := models.QueryLgUserAll()
	cur_user_menus := c.GetSession("cur_user_menus")
	cur_user := c.GetSession("cur_user")

	page:=tools.CreatePaging(1,len(data_list),len(data_list))
	c.Data["page"] = page

	c.Data["key"] = key
	c.Data["cur_user"] = cur_user
	c.Data["cur_user_menus"] = cur_user_menus
	c.Data["data_list"] = data_list
	c.Data["idc_list"] = idc_list
	c.Data["label_list"] = label_list
	c.Data["lguser_list"] = lguser_list
	c.Data["label"] = "主机管理"
	c.XSRFExpire = 7200
	c.Data["xsrf_token"] = c.XSRFToken()
	c.Layout = "base/base.html"
	c.LayoutSections = make(map[string]string)
	c.LayoutSections["Scripts"] = "cmdb/assetjs.html"
	c.TplName = "cmdb/asset.html"
}

func (c *AssetController) CreateAsset() {
	host_name := c.GetString("host_name")
	ip := c.GetString("ip")
	inner_ip := c.GetString("inner_ip")
	port,_ := c.GetInt("port",22)
	label_id,_ := c.GetInt("label_id",0)
	idc_id,_ := c.GetInt("idc_id",0)
	lguser_id,_ := c.GetInt("lguser_id",0)
	obj := models.Asset{}
	obj.HostName = host_name
	obj.Ip = ip
	obj.InnerIp = inner_ip
	obj.Port = port
	obj.LabelID = label_id
	obj.IdcID = idc_id
	obj.LgUserID = lguser_id
	models.AddAsset(obj)

	lgobj := models.QueryLgUserOne(lguser_id)
	user := lgobj.UserName
	passwd := lgobj.Password
	key_str :=  lgobj.Key

	// prepare arguments

	cli := tasks.Client()

	var salt_master string
	dict_obj1,err:= models.QueryDictKey("SALT_MASTER")
	dict_obj2,_:= models.QueryDictKey("DOWN_URL")
	if err != nil {
		salt_master = "127.0.0.1"
	}else{
		salt_master = dict_obj1.DictVal
	}
	down_url := dict_obj2.DictVal
	cmd := "hostname "+obj.HostName+" || hostnamectl set-hostname "+obj.HostName+";echo "+obj.HostName+" > /etc/hostname"+" ; yum install -y wget >& /dev/null ;  " +
		"wget -N -P /tmp/ "+down_url+"baseInstall.sh " +
		">& /dev/null && sh /tmp/baseInstall.sh "+ obj.Ip +" "+ salt_master
	// run task
	taskName := "task.SetHostConnect"
	asyncResult, err := cli.Delay(taskName, user, passwd, ip,key_str,cmd, port)
	if err != nil {
		panic(err)
	}
	if err != nil {
		c.Data["json"] = "添加失败，请看日志"
	}else{
		c.Data["json"] = "添加成功:"+asyncResult.TaskID
	}
	tk := models.LogTask{}
	cur_user := c.GetSession("cur_user")
	tk.UserName = cur_user.(string)
	tk.TaskName = fmt.Sprintf("安装 salt minion ：%s",ip)
	tk.Status = "PENDING"
	tk.TaskId = asyncResult.TaskID
	models.AddTask(tk)
	c.ServeJSON()
}

func (c *AssetController) GetIdAsset() {
	id,_ := c.GetInt("id",0)
	obj := models.QueryAssetOne(id)
	c.Data["json"] = obj
	c.ServeJSON()
}

func (c *AssetController) EditAsset() {
	id,_ := c.GetInt("id",0)
	host_name := c.GetString("host_name")
	ip := c.GetString("ip")
	inner_ip := c.GetString("inner_ip")
	port,_ := c.GetInt("port",22)
	label_id,_ := c.GetInt("label_id",0)
	idc_id,_ := c.GetInt("idc_id",0)
	lguser_id,_ := c.GetInt("lguser_id",0)
	obj := models.Asset{}
	obj.HostName = host_name
	obj.Ip = ip
	obj.InnerIp = inner_ip
	obj.Port = port
	obj.LabelID = label_id
	obj.IdcID = idc_id
	obj.LgUserID = lguser_id
	err := models.UpdateAsset(id,obj)
	if err != nil {
		c.Data["json"] = "更新失败，请看日志"
	}else{
		c.Data["json"] = "更细成功"
	}
	c.ServeJSON()
}

//删除
func (c *AssetController) DelAsset() {
	id,_:= c.GetInt("id", 0)
	models.DeleteAsset(id)
	c.Data["json"] = "删除成功"
	c.ServeJSON()
}

func (c *AssetController) DetailAsset() {
	id,_ := c.GetInt("id",0)
	asset_obj := models.QueryAssetDetail(id)
	if asset_obj.AssetOs.ID ==0{
		tasks.GetHostInfo(asset_obj.ID)
	}
	detail_obj := models.QueryAssetDetail(id)
	c.Data["json"] = detail_obj
	c.ServeJSON()
}

func (c *AssetController) SetBaseConfig() {
	//测试salt是否可用
	id,_ := c.GetInt("id",0)
	obj := models.QueryAssetOne(id)
	//_ = models.UpdateAsset(id,obj)
	status :=tools.TestSalt(obj.Ip)
	obj.Status = status
	_ = models.UpdateAsset(id,obj)
	c.Data["json"] = status
	c.ServeJSON()
}

func (c *AssetController) SyncAssetInfo() {
	asset_list := models.QueryAssetAll()
	taskName := "task.SyncAssetInfo"
	cli := tasks.Client()
	for _,v :=range asset_list{
		models.SyncAsset(v.ID)
		asyncResult,_ :=cli.Delay(taskName,v.ID)
		tk := models.LogTask{}
		cur_user := c.GetSession("cur_user")
		tk.UserName = cur_user.(string)
		tk.TaskName = fmt.Sprintf("同步资产信息 ：%s",v.Ip)
		tk.Status = "PENDING"
		tk.TaskId = asyncResult.TaskID
		models.AddTask(tk)
	}
	c.Data["json"] = "任务执行中，请耐心等待"
	c.ServeJSON()
}



